import React, { useEffect, useState } from 'react';
import { Typography, Space, Table, Modal, Form, Select, Button, Flex, Input } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import NewModal from './components/New';
import {
  apiMSDItemFilter,
  apiMSDItemList,
  apiMSDItemRemove,
  apiMSDItemDownload
} from '../../../services/masterData/item';
import { transformArray, download } from '../../../utils/commonUtil';
import DeleteConfirm from '../../Components/DeleteConfirm';
import {
  DROPDOWN,
  TEXTINPUT,
  NUMBERINPUT,
  TEXTAREA
} from '../../../utils/constant';
import './index.scss';

const Item = () => {
  const { t } = useTranslation();
  const { Title } = Typography;
  const [form] = Form.useForm();
  // 分页相关
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalPage, setTotalPage] = useState();
  // Approver Info 页面数据
  const [itemList, setItemList] = useState();
  // 下拉框数据
  const [buDropdownList, setBuDropdownList] = useState([]);
  const [itemDropdownList, setItemDropdownList] = useState([]);
  const [moduleList, setModuleList] = useState([]);

  const [openDrawer, setOpenDrawer] = useState(false);
  const [editType, setEditType] = useState('');
  const [recordData, setRecordData] = useState({});

  const columns = [
    {
      title: t('common.item'),
      dataIndex: 'itemName',
      width: 150,
      align: 'center'
    },
    {
      title: t('common.type'),
      dataIndex: 'itemType',
      width: 150,
      align: 'center'
    },
    {
      title: t('common.value'),
      width: 100,
      align: 'center',
      render: (text, record) => {
        if (record.itemType === DROPDOWN) {
          return <span className='value-td'>{record.dropdownTypeData}</span>;
        } else if (record.itemType === TEXTINPUT) {
          return <span className='value-td'>{record.textTypeData}</span>;
        } else if (record.itemType === NUMBERINPUT) {
          return <span className='value-td'>{record.numericTypeData}</span>;
        } else if (record.itemType === TEXTAREA) {
          return <span className='value-td'>{record.textareaTypeData}</span>;
        }
      },
    },
    {
      title: t('common.bu'),
      dataIndex: 'buType',
      width: 100,
      align: 'center'
    },
    {
      title: t('common.module'),
      dataIndex: 'moduleName',
      width: 150,
      align: 'center'
    },
    {
      title: t('common.remarks'),
      dataIndex: 'remark',
      width: 150,
      align: 'center'
    },
    {
      title: t('common.createdBy'),
      dataIndex: 'createdBy',
      width: 150,
      align: 'center'
    },
    {
      title: t('common.createTime'),
      dataIndex: 'createdTime',
      width: 150,
      align: 'center'
    },
    {
      title: t('common.updateTime'),
      dataIndex: 'updatedTime',
      width: 150,
      align: 'center'
    },
    {
      title: ' ',
      width: 150,
      align: 'center',
      render: (_, record) => (
        <Space size={2}>
          <Button type="link" className='blue' size='small' onClick={() => detailClickHandle(record, 'view')}>{t('common.view')}</Button>
          <Button type="link" className='blue' size='small' onClick={() => detailClickHandle(record, 'edit')}>{t('common.edit')}</Button>
          <Button type="link" className='red' size='small' onClick={() => clickDelete(record)}>{t('common.delete')}</Button>
        </Space>
      ),
    },
  ];

  const serach = () => {
    setCurrentPage(1);
    queryList(1);
  }

  // 获取页面list数据
  const queryList = async (pagination, size) => {
    const formData = form.getFieldsValue();
    const params = {
      buTypes: formData.buTypes || [],
      moduleNames: formData.moduleNames || [],
      items: formData.items || [],
      createdBy: formData.createdBy || '',
      page: pagination || currentPage,
      limit: size || pageSize
    };
    apiMSDItemListAsync(params);
  }
  // 调用页面list数据api
  const apiMSDItemListAsync = (params) => {
    apiMSDItemList(params).then((res) => {
      const data = res?.data?.data;
      setItemList(data?.items);
      setTotalPage(data?.total);
    });
  }

  // 调用下拉框api
  const apiMSDItemFilterAsync = () => {
    apiMSDItemFilter().then((res) => {
      const data = res?.data?.data;
      setBuDropdownList(transformArray(data?.buTypes));
      setModuleList(transformArray(data?.moduleNames));
      setItemDropdownList(transformArray(data?.items))
    });
  }

  // 点击下载按钮
  const clickDownload = () => {
    const formData = form.getFieldsValue();
    const params = {
      buTypes: formData.buTypes || [],
      moduleNames: formData.moduleNames || [],
      items: formData.items || [],
      createdBy: formData.createdBy || ''
    };
    apiMSDItemDownload(params).then((res) => {
      if (res?.data) {
        download(res)
      }
    })
  }

  const detailClickHandle = (record, type) => {
    setRecordData(record);
    setOpenDrawer(true);
    setEditType(type);
  };

  // 点击删除按钮
  const clickDelete = (data) => {
    DeleteConfirm({
      t,
      title: t('common.deleteMsg'),
      onOk () {
        const params = {
          id: data?.itemMaintenanceId
        }
        apiMSDItemRemove(params).then(() => {
          queryList();
        });
      }
    });
  }

  useEffect(() => {
    queryList();
    apiMSDItemFilterAsync();
  }, [])
  return (
    <>
      <div className='page-title-wrap'>
        <Flex align='center' gap="middle" justify='space-between'>
          <Title className='fontStyleH2' level={2} >{t('layout.item')}</Title>
          <div>
            <Button
              type="primary"
              ghost
              className='newBtn'
              onClick={() => {
                clickDownload();
              }}
            >
              {t('common.download')}
            </Button>
            <Button
              type="primary"
              className='newBtn'
              onClick={() => {
                setOpenDrawer(true);
                setEditType('new');
              }}
            >
              {t('common.new')}
            </Button>
          </div>
        </Flex>
      </div>

      <div className='page-content-wrap item-list-wrap'>
        <Form name="nest-messages" form={form} className='filter-wrap'>
          <Flex align='center' gap="middle">
            <Form.Item name="buTypes"
              label={t('common.bu')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={buDropdownList} />
            </Form.Item>
            <Form.Item name="moduleNames"
              label={t('common.module')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={moduleList} />
            </Form.Item>
            <Form.Item name="items"
              label={t('common.item')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={itemDropdownList} />
            </Form.Item>
            <Form.Item name="createdBy"
              label={t('common.createdBy')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Input allowClear placeholder={t('common.pleaseEnter')} />
            </Form.Item>

            <Button
              className='search-btn'
              type="primary"
              onClick={serach}
              icon={<SearchOutlined style={{ fontSize: 20 }} />}
            />
          </Flex>
        </Form>
        <Table
          columns={columns}
          dataSource={itemList}
          size="small"
          pagination={{
            total: totalPage,
            current: currentPage,
            pageSize: pageSize,
            onChange: (_crrentPage, _pageSize) => {
              setCurrentPage(_crrentPage);
              setPageSize(_pageSize);
              queryList(_crrentPage, _pageSize);
            },
            pageSizeOptions: [10, 20, 50],
            showSizeChanger: true,
            showTotal: (total) => {
              return t(`common.totalItems`, { total: total });
            },
          }}
        />
      </div>
      {
        openDrawer &&
        <NewModal
          openDrawer={openDrawer}
          setOpenDrawer={setOpenDrawer}
          editSucessFn={() => { queryList(); apiMSDItemFilterAsync(); }}
          editType={editType}
          recordData={recordData}
        />
      }
    </>
  )
};

export default Item;